package com.personal.dao.handler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Locale;

import com.personal.dao.configuration.Configuration;
import com.personal.dao.metadata.DataBaseFieldMetadata;
import com.personal.dao.metadata.DataBaseTableMetadata;
import com.personal.dao.reflection.MetaObject;
import com.personal.dao.type.TypeHandler;

/**
 * 处理工具类
 * @author cuibo
 *
 */
public class HandlerUtil
{

    /**
     * 将ResultSet的查询结果设置给t
     * @param rs
     * @param rsMeta
     * @param matadata
     * @param t
     * @throws SQLException 
     */
    public static <T> void setResultData2MetaObject(ResultSet rs, ResultSetMetaData rsMeta, DataBaseTableMetadata<T> metadata,
            T t) throws SQLException
    {
        MetaObject metaObject = Configuration.getInstance().newMetaObject(t);
        int colCount = rsMeta.getColumnCount();
        for (int i = 1; i <= colCount; i++)
        {
            String columnLabel = rsMeta.getColumnLabel(i);
            // 获取列名对应的字段名：忽略大小写
            DataBaseFieldMetadata field = metadata == null ? null
                    : metadata.getDataBaseFieldMetadataByColumnName(columnLabel.toLowerCase(Locale.ENGLISH));
            // 获取值，需要根据类型
            if (field != null)
            {
                // 获取类型转换
                TypeHandler<?> handler = Configuration.getInstance().getTypeHandlerRegistry()
                        .getTypeHandler_cuibo(field.getC());
                if (handler == null)
                {
                    handler = Configuration.getInstance().getTypeHandlerRegistry().getUnknownTypeHandler();
                }
                metaObject.setValue(field.getFieldName(), handler.getResult(rs, i));
            } else
            {
                // 判断是否有Setter。有则设置值
                if (metaObject.hasSetter(columnLabel))
                {
                    // 获取类型
                    TypeHandler<?> handler = Configuration.getInstance().getTypeHandlerRegistry()
                            .getTypeHandler_cuibo(metaObject.getGetterType(columnLabel));
                    if (handler == null)
                    {
                        handler = Configuration.getInstance().getTypeHandlerRegistry().getUnknownTypeHandler();
                    }
                    metaObject.setValue(columnLabel, handler.getResult(rs, i));
                }
            }
        }
    }

}
